import axios from 'axios'
import store from '../store/index'
axios.defaults.timeout = 50000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

import { ElLoading as Loading, ElMessage as Message } from 'element-plus';


let loadingInstance;
let loadingStatus = false;
if (process.env.NODE_ENV == 'development') {
    
    axios.defaults.baseURL = 'http://127.0.0.1:7881/';
}
else if (process.env.NODE_ENV == 'staging') {

    axios.defaults.baseURL = 'http://awase1slfmlnx02.corp.jabil.org:8002/safety_for_all_api/';
}

else if (process.env.NODE_ENV == 'production') {
    axios.defaults.baseURL = 'http://awase1slfmlnx02.corp.jabil.org:8001/safety_for_all_api/';
}
if (!axios.defaults.baseURL.endsWith('/')) {
    axios.defaults.baseURL+="/";
}
let ipAddress = axios.defaults.baseURL;
axios.interceptors.request.use((config) => {
    return config;
}, (error) => {
    return Promise.reject(error);
});

axios.interceptors.response.use(
    (res) => {
        closeLoading();
        checkResponse(res);
        return Promise.resolve(res);
    },
    (error) => {
        closeLoading();
        let httpMessage = '';

        if (error.response) {
            const { status, data } = error.response;

            if (status === 401 && data?.code === 401) {
                if (!localStorage.getItem('user')) {
                    // Message.error({
                    //     showClose: true,
                    //     message: '登陆已过期',
                    //     type: 'error'
                    // });
                }
                toLogin();
                return;
            }

            if (status === 404) {
                httpMessage = "未找到请求地址";
            } else if (data?.message) {
                httpMessage = data.message;
            }
        } else {
            httpMessage = '服务器处理异常';
        }

        redirect(httpMessage);
        return Promise.reject(error.response || {}, httpMessage);
    }
);




function closeLoading () {
    if (loadingInstance) {
        loadingInstance.close();
    }
    if (loadingStatus) {
        loadingStatus = false;
        if (loadingInstance) {
            loadingInstance.close();
        }
    }

}
function checkResponse(res) {
    // 刷新token
    if (res.getResponseHeader) {
        // 检查响应头中是否包含 vol_exp
        if (res.getAllResponseHeaders().indexOf("vol_exp") >= 0) {
            if (res.getResponseHeader("vol_exp") == "1") {
                replaceToken();
            }
        }
    } else if (res.headers && res.headers.vol_exp == "1") {
        replaceToken();
    }
}

const _Authorization = 'Authorization';

function showLoading (loading) {
    if (!loading || loadingStatus) {
        return;
    }
    loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        customClass:"http-loading",
        background: typeof loading == "string" ? loading : '正在处理.....',
    });
}
function setHeaderLang (_header) {
    let langType = localStorage.getItem(lang_storage_key);
    if (langType == 'zh-CN') {
        _header["lang"] = "zh-CN";
        return;
    }
    _header['lang'] = langType;
}
function getToken () {
    return store.getters.getToken();
}

/*
  url
  params请求后台的参数,如：{name:123,values:['a','b','c']}
  loading是否显示遮罩层,可以传入true.false.及提示文本
  config配置信息,如{timeout:3000,headers:{token:123}}
*/
function post (url, params, loading, config) {
    url = url.replace(/_/g, "");
    showLoading(loading);
    setHeaderLang(axios.defaults.headers);
    axios.defaults.headers[_Authorization] = getToken();
    return new Promise((resolve, reject) => {
        axios.post(url, params, config)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err?.data?.message ? err.data.message : '服务器处理异常');
            })
            .catch((error) => {
                reject(error)
            })
    })
}

//=true异步请求时会显示遮罩层,=字符串，异步请求时遮罩层显示当前字符串
function get (url, param, loading, config) {
    url = url.replace(/_/g, "");
    showLoading(loading);
    setHeaderLang(axios.defaults.headers);
    axios.defaults.headers[_Authorization] = getToken();
    return new Promise((resolve, reject) => {
        axios.get(url, config)
            .then(response => {
                resolve(response.data)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

//url:url地址
//params:请求参数
//fileName:下载的文件名
//loading:是否显示加载状态
function download(url, params, fileName, loading, callback) {
    fileName = fileName.replace(">", "＞").replace("<", "＜");
    setHeaderLang(axios.defaults.headers);

    post(url, params, loading, { responseType: 'blob' }).then(content => {
        const blob = new Blob([content]);
        const downloadFile = (blob, fileName) => {
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        };

        if ('download' in document.createElement('a')) { // 非IE下载
            downloadFile(blob, fileName);
        } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }

        if (callback) callback();
    }).catch(error => {
        console.error('Download failed:', error);
    });
}


function createXHR () {
    if (XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject) {
        if (typeof ActiveXObject.activeXString !== "string") {
            const versions = [
                "MSXML2.XMLHttp.6.0",
                "MSXML2.XMLHttp",
                "MSXML2.XMLHttp.3.0"
            ];
            for (const version of versions) {
                try {
                    new ActiveXObject(version);
                    ActiveXObject.activeXString = version;
                    break;
                } catch (e) {
                    console.log(e);
                }
            }
        }
        return new ActiveXObject(ActiveXObject.activeXString);
    }
}

function redirect(responseText, message) {
    try {
        const responseData = typeof responseText === 'string' ? JSON.parse(responseText) : responseText;
        const isUnauthorized = (data) => data?.code === 401;

        if (isUnauthorized(responseData) || isUnauthorized(responseData.data)) {
            closeLoading();
            toLogin();
        } else if (message) {
            showMessage(message, 'error');
        }
    } catch (error) {
        console.error(error);
        showMessage(responseText, 'error');
    }
}

function showMessage(message, type) {
    Message.error({
        showClose: true,
        message: message,
        type: type
    });
}

function toLogin () {
    if (window.location.hash) {
        window.location.href = window.location.origin + '/#/login?'+Math.random()
        return
    }
    window.location.href = window.location.origin + '/login?'+Math.random()
}
//动态刷新token
function replaceToken () {
    setHeaderLang(axios.defaults.headers);
    ajax({
        url: "/api/User/replaceToken",
        param: {},
        json: true,
        success: function (x) {
            if (x.status) {
                let userInfo = store.getters.getUserInfo();
                userInfo.token = x.data;
                store.commit('setUserInfo', userInfo);
            } else {
                console.log(x.message);
                toLogin();
            }
        },
        errror: function (ex) {
            console.log(ex);
            toLogin();
        },
        type: "post",
        async: false
    });


}

function ajax(param) {
    let httpParam = Object.assign({
        url: '',
        headers: {},
        param: {},
        json: true,
        success: function () { },
        error: function () { },
        type: 'post',
        async: true
    }, param);

    // console.log('找到url', httpParam.url)

    httpParam.url = axios.defaults.baseURL + httpParam.url.replace(/\/?/, '');

    let token = getToken();

    // 确保 headers 对象已初始化
    if (!httpParam.headers) {
        httpParam.headers = {};
    }

    httpParam.headers['Authorization'] = token;

    let xhr = createXHR();
    xhr.onreadystatechange = function () {
        if (xhr.status == 403 || xhr.status == 401) {
            redirect(xhr.responseText);
            return;
        }
        checkResponse(xhr);
        if (xhr.readyState == 4 && xhr.status == 200) {
            httpParam.success(httpParam.json ? JSON.parse(xhr.responseText) : xhr.responseText);
            return;
        }
        if (xhr.status != 0 && xhr.readyState != 1) {
            httpParam.error(xhr);
        }
    };

    // 初始化请求
    xhr.open(
        httpParam.type,
        httpParam.url,
        httpParam.async
    );
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    for (const key in httpParam.headers) {
        xhr.setRequestHeader(key, httpParam.headers[key]);
    }

    let dataStr = '';
    for (const key in httpParam.param) {
        dataStr += key + "=" + httpParam.param[key] + "&";
    }
    dataStr = dataStr.slice(0, -1); // 去掉最后一个 "&"

    try {
        xhr.send(dataStr);
    } catch (error) {
        toLogin();
    }
}


ajax.post = function (url, param, success, errror) {
    // console.log('url666',url)
    ajax({ url: url, param: param, success: success, error: errror, type: 'post' })
}
ajax.get = function (url, param, success, errror) {
    // console.log('url66777',url)
    ajax({ url: url, param: param, success: success, error: errror, type: 'get' })
}
export default { post, get,download, ajax, ipAddress }
